import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

let cancelArr = []

// 跳转页面时取消所有请求，在路由导航守卫中触发
export function cancelAll() {
  cancelArr = cancelArr.filter((item) => {
    item.cancel()
    return false
  })
}

_axios.interceptors.request.use(
  (config) => {
    // 同一接口调用时取消上一次调用
    cancelArr = cancelArr.filter((item) => {
      if (item.url === config.url && item.method === config.method) {
        item.cancel()
        return false
      }
    })
    // axios 取消功能
    config.cancelToken = new axios.CancelToken((cancel) => {
      cancelArr.push({
        url: config.url,
        method: config.method,
        cancel: cancel
      })
    })
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

_axios.interceptors.response.use(
  (res) => {
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    if (error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?redirect=' + location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)

export default _axios
